package com.hongdee.insurance.commission.service.impl;

import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.insurance.Constant;
import com.hongdee.insurance.commission.dao.ITCommissionDao;
import com.hongdee.insurance.commission.entity.TInsuranceCommission;
import com.hongdee.insurance.commission.entity.TInsuranceCommissionExamLog;
import com.hongdee.insurance.commission.service.ITCommissionSrevice;
import com.hongdee.insurance.company.entity.TInsuranceCompany;
import com.hongdee.insurance.company.service.ITInsuranceCompanyService;
import com.hongdee.insurance.order.entity.TInsuranceOrderExamLog;
import com.hongdee.insurance.order.service.ITInsuranceOrderStatsticsService;
import com.hongdee.insurance.quotation.entity.TInsuranceQuotation;
import com.hongdee.insurance.quotation.service.ITInsuranceQuotationService;
import com.hongdee.insurance.quotationitem.service.ITInsuranceQuotationItemService;
import com.hongdee.rbac.dept.entity.TBcOrgan;
import com.hongdee.rbac.dept.service.ITBcOrganService;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Mr. Xu on 2017/4/25.
 */
@Service
public class TCommissionSreviceImpl implements ITCommissionSrevice {
    @Autowired
    private ITCommissionDao itCommissionDao;
    private String tabName = "T_Insurance_Commission";
    private String tabEntity = "TInsuranceCommission";
    private static String defaultDatePattern = "yyyy-MM-dd";
    @Autowired
    private ITInsuranceQuotationService insuranceQuotationService;

    @Autowired
    private ITInsuranceOrderStatsticsService statsticsService;
    @Autowired
    private ITInsuranceCompanyService companyService;
    @Autowired
    private ITBcOrganService organService;
    @Autowired
    private ITInsuranceQuotationItemService insuranceQuotationItemService;

    /**
     *
     * @param uid
     * @param start
     * @param limit
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public Map applyUnitPage(String uid, String start, String limit, Map data) throws Exception {
        String companyId=TokenUtil.getCompanyId(uid);
        Map organ= organService.info(companyId);
        StringBuffer sql = new StringBuffer();
        List<String> params=new ArrayList<>();
        sql.append(" select * from ( ");
        sql.append("select * from (");
        sql.append("select t.id, t.create_time, t.create_user, t.update_time, t.update_user, c.insurance_company_name," +
                " CONCAT(t.commission,'%') commission, t.commission_type, t.company_id, t.insurance_type, t.start_date, " +
                " t.stop_date, t.insure_type, t.apply_unit,t.apply_unit_name as oName,t.remark,t.status,t.area," +
                " area.label disp ,case when t.iscompulsoryinsurance='0' then '单交强' when t.iscompulsoryinsurance='1' then '单商业'" +
                " when t.iscompulsoryinsurance ='2' then '交商共保' end iscompulsoryinsurance" +
                " from " + tabName + " t " +
                " left JOIN t_insurance_company c  on t.company_id=c.id " +
                " left JOIN (select * from t_bc_newdict where p_code='area') area ON t.area=area.code" +
                " where t.status='1' and  t.area=? and t.apply_unit='0' ");
        params.add(StringUtil.formatEmpty(organ.get("oArea")));
        if (data.get("date") != null && !data.get("date").toString().equals("")) {
            sql.append(" and DATE_FORMAT(t.start_date,'%Y%m')=DATE_FORMAT(?,'%Y%m') ");
            String time=DateUtils.monthSToStrTime(StringUtil.formatEmpty(data.get("date")));
            params.add(time);
        }else{
            sql.append(" and DATE_FORMAT(t.start_date,'%Y%m')=DATE_FORMAT(NOW(),'%Y%m') ");
        }
        if(!"".equals(StringUtil.formatEmpty(data.get("insuranceCompanyId")))){
            sql.append(" and t.company_id=? ");
            params.add(StringUtil.formatEmpty(data.get("insuranceCompanyId")));
        }
        if(!"".equals(StringUtil.formatEmpty(data.get("iscompulsoryinsurance")))){
            sql.append(" and t.iscompulsoryinsurance=? ");
            params.add(StringUtil.formatEmpty(data.get("iscompulsoryinsurance")));
        }

        sql.append(" union ");
        sql.append("select t.id, t.create_time, t.create_user, t.update_time, t.update_user, c.insurance_company_name," +
                " CONCAT(t.commission,'%') commission, t.commission_type, t.company_id, t.insurance_type, t.start_date, " +
                " t.stop_date, t.insure_type, t.apply_unit,t.apply_unit_name as oName,t.remark,t.status,t.area,area.label disp ," +
                " case when t.iscompulsoryinsurance='0' then '单交强' when t.iscompulsoryinsurance='1' then '单商业'" +
                " when t.iscompulsoryinsurance ='2' then '交商共保' end iscompulsoryinsurance" +
                " from " + tabName + " t " +
                " left JOIN t_insurance_company c  on t.company_id=c.id " +
                " left JOIN (select * from t_bc_newdict where p_code='area') area ON t.area=area.code" +
                " where t.status='1' and  t.area=? and t.apply_unit=? ");
        params.add(StringUtil.formatEmpty(organ.get("oArea")));
        params.add(companyId);
        if (data.get("date") != null && !data.get("date").toString().equals("")) {
            sql.append(" and DATE_FORMAT(t.start_date,'%Y%m')=DATE_FORMAT(?,'%Y%m') ");
            String time=DateUtils.monthSToStrTime(StringUtil.formatEmpty(data.get("date")));
            params.add(time);
        }else{
            sql.append(" and DATE_FORMAT(t.start_date,'%Y%m')=DATE_FORMAT(NOW(),'%Y%m') ");
        }
        if(!"".equals(StringUtil.formatEmpty(data.get("insuranceCompanyId")))){
            sql.append(" and t.company_id=? ");
            params.add(StringUtil.formatEmpty(data.get("insuranceCompanyId")));
        }
        if(!"".equals(StringUtil.formatEmpty(data.get("iscompulsoryinsurance")))){
            sql.append(" and t.iscompulsoryinsurance=? ");
            params.add(StringUtil.formatEmpty(data.get("iscompulsoryinsurance")));
        }
        sql.append(") temp ORDER BY company_id DESC,start_date ASC,insurance_type desc,insure_type desc ");
        sql.append(") temp ");

        return this.itCommissionDao.page(sql.toString(),params.toArray(),start,limit);
    }
    /**
     * 佣金分页查询
     *
     * @param uid
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public Map page(String uid, String start, String limit, Map data) throws Exception {
        StringBuffer sql = new StringBuffer();
        sql.append(" select * from ( ");
        sql.append("select t.id, t.create_time, t.create_user, t.update_time, t.update_user, c.insurance_company_code," +
                " CONCAT(t.commission,'%') commission, t.commission_type, t.company_id, t.insurance_type, t.start_date, " +
                " t.stop_date, t.insure_type, t.apply_unit,o.o_name,t.remark,t.status,t.area,area.label disp from " + tabName + " t left join t_bc_organ o " +
                " on " +
                " t.apply_unit=o.id " +
                " left JOIN t_insurance_company c  on t.company_id=c.id " +
                " left JOIN (select * from t_bc_newdict where p_code='area') area ON t.area=area.code" +
                " where t.apply_unit<>'0' ");
        List params = new ArrayList();
        if(!"0".equals(TokenUtil.getCompanyId(uid))){
            sql.append(" and t.create_company_id=? ");
            params.add(TokenUtil.getCompanyId(uid));
        }else{
            List<Map<String,Object>> list=TokenUtil.getDataCompany(uid);
            sql.append("  and t.create_company_id in( ");
            for (int i = 0; i < list.size(); i++) {
                String id= StringUtil.formatEmpty(list.get(i).get("id"));
                sql.append("?,");
                params.add(id);
            }
            sql.append("?");
            params.add(TokenUtil.getCompanyId(uid));
            sql.append(" ) ");
        }
        if(!"".equals(StringUtil.formatEmpty(data.get("applyUnitId")))){
            sql.append(" and t.apply_unit=? ");
            params.add(StringUtil.formatEmpty(data.get("applyUnitId")));
        }
        this.queryCommissionPageToSql(sql,data,params);
        sql.append(" union all ");
        sql.append("select t.id, t.create_time, t.create_user, t.update_time, t.update_user, c.insurance_company_code," +
                " CONCAT(t.commission,'%') commission, t.commission_type, t.company_id, t.insurance_type, t.start_date, " +
                " t.stop_date, t.insure_type, t.apply_unit,o.o_name,t.remark,t.status,t.area,area.label disp from " + tabName + " t left join t_bc_organ o " +
                " on " +
                " t.apply_unit=o.id " +
                " left JOIN t_insurance_company c  on t.company_id=c.id " +
                " left JOIN (select * from t_bc_newdict where p_code='area') area ON t.area=area.code" +

                " where t.apply_unit='0' ");
        this.queryCommissionPageToSql(sql,data,params);
        sql.append(" ) temp  ");
        sql.append(" ORDER BY temp.company_id DESC,temp.start_date ASC,temp.insurance_type desc,temp.insure_type desc ");
        return this.itCommissionDao.page(sql.toString(), params.toArray(), start, limit);
    }

    @Override
    public void queryCommissionPageToSql(StringBuffer sql,Map data,List params) throws Exception {
        if(!"".equals(StringUtil.formatEmpty(data.get("companyId")))){
            sql.append(" and t.company_id=? ");
            params.add(data.get("companyId"));
        }
        //筛选佣金日期
        if (data.get("date") != null && !data.get("date").toString().equals("")) {
            sql.append(" and DATE_FORMAT(t.start_date,'%Y%m')=DATE_FORMAT(?,'%Y%m') ");
            String time=DateUtils.monthSToStrTime(StringUtil.formatEmpty(data.get("date")));
            params.add(time);
        }else{
            sql.append(" and DATE_FORMAT(t.start_date,'%Y%m')=DATE_FORMAT(NOW(),'%Y%m') ");
        }
        //保险类别
        if (data.get("insuranceType") != null && !data.get("insuranceType").toString().equals("")) {
            sql.append(" and  t.insurance_type =? ");
            params.add(data.get("insuranceType"));
        }
        //投保类别
        if (data.get("insureType") != null && !data.get("insureType").toString().equals("")) {
            sql.append(" and t.insure_type=?  ");
            params.add(data.get("insureType"));
        }
        //佣金类别
        if (data.get("commissionType") != null && !data.get("commissionType").toString().equals("")) {
            sql.append(" and t.commission_type=? ");
            params.add(data.get("commissionType"));
        }
        if(data.get("oArea")!=null && !"".equals(StringUtil.formatEmpty(data.get("oArea")))){
            sql.append(" and t.area=? ");
            params.add(data.get("oArea"));
        }
        /**
         * 审核状态
         */
        if(data.get("status")!=null && !"".equals(StringUtil.formatEmpty(data.get("status")))){
            sql.append(" and t.status=? ");
            params.add(data.get("status"));
        }
        /**
         * 保单类别
         */
        if(!"".equals(StringUtil.formatEmpty(data.get("iscompulsoryinsurance")))){
            sql.append(" and t.iscompulsoryinsurance=? ");
            params.add(StringUtil.formatEmpty(data.get("iscompulsoryinsurance")));
        }

    }


    /**
     * 历史时间比较
     */
    private List<TInsuranceCommission> hisDateCompare(TInsuranceCommission entity,List<String> carCompanyList,String uid) throws Exception {
        List<TInsuranceCommission> list=new ArrayList<>();
        String companyId=TokenUtil.getCompanyId(uid);
        for (String key:carCompanyList) {
            TInsuranceCommission insuranceCommission=new TInsuranceCommission();
            BeanUtils.copyProperties(entity,insuranceCommission);
            String[] keys=key.split("_");
            String applyUnit=keys[0];
            String companyName="";
            if(!"0".equals(keys[0])){
                companyName=keys[1];
            }
            insuranceCommission.setApplyUnit(applyUnit);
            String commissionId="";
            if("".equals(insuranceCommission.getId()) || null==insuranceCommission.getId()){
                insuranceCommission.setCreateTime(System.currentTimeMillis());
                insuranceCommission.setCreateUser(uid);
                insuranceCommission.setUpd(false);
                insuranceCommission.setStatus(String.valueOf(Constant.COMMISSION_STATUS.argee.ordinal()));
            }else{
                commissionId=insuranceCommission.getId();
                //判断佣金修改
                checkUpdCommissionByTime(commissionId);
                insuranceCommission.setUpdateTime(System.currentTimeMillis());
                insuranceCommission.setUpdateUser(uid);
                insuranceCommission.setUpd(true);
            }
            insuranceCommission.setCreateCompanyId(companyId);
            //新增或修改 佣金设置为待审核状态
//            insuranceCommission.setStatus(String.valueOf(Constant.COMMISSION_STATUS.init.ordinal()));
            StringBuffer sqlBuf = new StringBuffer();
            sqlBuf.append(" select * from " + tabName + " where insurance_type = ? and insure_type=? and commission_type = ? and company_id =? " +
                    " and apply_unit=? and area=? and status='1'");

            List params = new ArrayList();
            params.add(entity.getInsuranceType());
            params.add(entity.getInsureType());
            params.add(entity.getCommissionType());
            params.add(entity.getCompanyId());
            params.add(applyUnit);
            params.add(entity.getArea());
            //编辑时 排除本身
            if(!"".equals(commissionId)){
                sqlBuf.append(" and id<>? ");
                params.add(commissionId);
            }
            sqlBuf.append(" order by stop_date desc ");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar date = Calendar.getInstance();
            date.setTime(sdf.parse(entity.getStartDate()));
            date.set(Calendar.DATE, date.get(Calendar.DATE) - 1);
            //常规佣金
            if (entity.getCommissionType() != null && entity.getCommissionType().toString().equals("0")) {
                List<Map<String, Object>> data = this.itCommissionDao.list(sqlBuf.toString(), params.toArray());
                if (data.size() != 0) {
                    this.checkCommissionDate(data,companyName+"常规佣金起止时间重叠!!",entity);
                }
            }
            //促销佣金
            if (entity.getCommissionType() != null && entity.getCommissionType().toString().equals("1")) {
                List<Map<String, Object>> data = this.itCommissionDao.list(sqlBuf.toString(), params.toArray());
                if (data.size() != 0) {
                    this.checkCommissionDate(data,companyName+"促销佣金起止时间重叠!!",entity);
                }
            }
            list.add(insuranceCommission);
        }
        return list;
    }

    /**
     * 更新佣金率信息
     * @param commissionId
     * @throws Exception
     */
    @Override
    public void updOrderItemCommissionPrice(String commissionId,String companyId) throws Exception {
        String sql=" update " +
                " t_insurance_order_item item, " +
                " t_insurance_commission tic " +
                " set item.commission=tic.commission, " +
                " item.commission_price=ROUND(item.price*1*(tic.commission/100),2) " +
                " WHERE " +
                " tic.id = item.commission_id " +
                " AND item.blance_type = '0' " +
                " AND item.is_commission_temp = 'false'" +
                " AND item.commission_id=?";
        this.itCommissionDao.executeSQL(sql,commissionId);
        statsticsService.updOrderToStatistics(companyId);
    }

    /**
     * 检测时间是否有相同的
     * @param data
     * @param tpl
     * @param entity
     * @throws Exception
     */
    @Override
    public void checkCommissionDate(List<Map<String,Object>> data,String tpl,TInsuranceCommission entity) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar date = Calendar.getInstance();
        for (Map tempMap : data) {
            Long begin = sdf.parse(String.valueOf(tempMap.get("startDate"))).getTime();
            Long end = sdf.parse(String.valueOf(tempMap.get("stopDate"))).getTime();
            //新增佣金起止时间与历史数据起止时间重叠
            Long start=sdf.parse(entity.getStartDate()).getTime();
            Long stop=sdf.parse(entity.getStopDate()).getTime();
            boolean flag=true;
            if(begin>=start && begin<=stop){
                flag=false;
            }
            if(begin<=start && end>=stop){
                flag=false;
            }
            if(begin<=start && end<=stop && end>start){
                flag=false;
            }
            if(end<=stop && begin>=start){
                flag=false;
            }
            if(begin>=start && end>=stop && begin<stop){
                flag=false;
            }
            if(!flag){
                throw new Exception(tpl);
            }
        }
    }

    /**
     * 修改的话 检测是否在当月
     * @param commissionId
     * @throws Exception
     */
    public void checkUpdCommissionByTime(String commissionId) throws Exception {
        //获得佣金详情
        TInsuranceCommission commission=this.itCommissionDao.getInsuranceCommissionById(commissionId);
        //判断开始时间是否在本月
        String startDate=commission.getStartDate();
        String nowTime=DateUtils.getTimeStr(DateUtils.YYYYMMDD);
        Long startL=DateUtils.dayToLongTime(startDate);
        Long monthStart=DateUtils.monthSToLongTime(nowTime);
        Long monthEnd=DateUtils.addMonthLongTime(monthStart,+1);//下月一号
        if(startL<monthStart || startL>=monthEnd){
            throw new Exception("只允许修改当月佣金信息!!");
        }
    }

    /**
     * 佣金明细
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Map info(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择一项佣金！");
        }
        String sql="select id, create_time, create_user, dept_id, update_time, update_user, apply_unit, commission, " +
                " commission_type, company_id, insurance_type, insure_type, start_date, stop_date, area, remark, status, " +
                " create_company_id, group_code, iscompulsoryinsurance, apply_unit_name from t_insurance_commission" +
                " where id=?";
        return this.itCommissionDao.info(sql,id);
    }

    /**
     * 新增或者修改佣金
     *
     * @param data
     * @return
     * @throws Exception
     */
    @Override
    public void saveOrUpdate(TInsuranceCommission data, String uid,List<String> carCompanyList) throws Exception {
        if("".equals(data.getCompanyId()) || null==data.getCompanyId()){
            throw new Exception("请选择保险公司！");
        }
        String companyId=TokenUtil.getCompanyId(uid);
        List<TInsuranceCommission> list=this.hisDateCompare(data,carCompanyList,uid);
        this.itCommissionDao.saveOrUpdateList(list);
        //修改佣金对应的保单信息
        for(TInsuranceCommission commission:list){
            if(commission.isUpd()){
                this.updOrderItemCommissionPrice(commission.getId(),companyId);
            }
        }

    }

    /**
     * 获得公司信息
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> getCarCompanys(String area) throws Exception {
        String sql=" select '0_全部' id,'全部' o_name union all " +
                "select  CONCAT(id,'_',o_name) id,o_name from t_bc_organ where o_p_id in( " +
                " select id from t_bc_organ where o_p_id in( " +
                " select id from t_bc_organ where o_p_id='0' " +
                " ) ) and o_area=?";
        return this.itCommissionDao.list(sql,area);
    }

    @Override
    public List<Map<String, Object>> getCarCompanysToBill() throws Exception {
        String sql=" " +
                "select  id,o_name from t_bc_organ where o_p_id in( " +
                " select id from t_bc_organ where o_p_id in( " +
                " select id from t_bc_organ where o_p_id='0' " +
                " ) ) ";
        return this.itCommissionDao.list(sql);
    }


    /**
     * 根据保险公司、投保类别、投保开始时间 获得该保险公司所设置的佣金
     * @param id
     * @return
     */
    @Override
    public Map<String,Object> getCarInsuranceCommissionById(String id,String time,String uid,String iscompulsoryinsurance,
                                                            String companyId) throws Exception {
        Long timeL=DateUtils.dayToLongTime(time);
        String nowTime=DateUtils.getTimeStr(DateUtils.YYYYMMDD);
        Long nowTimeL=DateUtils.dayToLongTime(nowTime);
        //当前时间
        if(timeL>nowTimeL){
            throw new Exception("出单日期日期不正确，不能选择大于今天的时间！！");
        }
        TInsuranceQuotation insuranceQuotation=this.insuranceQuotationService.getInsuranceQuotationById(id);
        if(!"".equals(iscompulsoryinsurance)){
            insuranceQuotation.setIscompulsoryinsurance(iscompulsoryinsurance);
        }
        String insuranceTypeName="续保";
        if("sb".equals(insuranceQuotation.getInsureType())){
            insuranceTypeName="新保";
        }

        TInsuranceCompany company=companyService.getInfo(insuranceQuotation.getInsuranceCompanyId());
        if(company==null){
            throw new Exception("未找到保险公司!!");
        }
        Map<String,Object> jqMap=this.getInsureanceJqAndSy(insuranceQuotation,time,uid,"0",company,companyId);
        Map<String,Object> syMap=this.getInsureanceJqAndSy(insuranceQuotation,time,uid,"1",company,companyId);
        Map<String,Object> ccsMap=this.getInsureanceJqAndSy(insuranceQuotation,time,uid,"2",company,companyId);


        StringBuffer errStr=new StringBuffer("["+company.getInsuranceCompanyName()+"]   ");
        boolean errFlag=false;
        if(jqMap==null) {
            if(!String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()).equals(iscompulsoryinsurance)) {
                errFlag = true;
                errStr.append("交强险未设置" + insuranceTypeName + "佣金;");
            }
        }
        if(syMap==null){
            if(!String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()).equals(iscompulsoryinsurance)) {
                errFlag = true;
                errStr.append("商业险未设置" + insuranceTypeName + "佣金;");
            }
        }

        if(errFlag){
            throw new Exception(errStr.toString());
        }
        Map<String,Object> map=new HashMap<>();
        map.put("jq",jqMap);
        map.put("sy",syMap);
        map.put("ccs",ccsMap);
        return map;
    }

    /**
     * 生成报价点，出单
     * @param id
     * @param time
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public Map<String,Object> getCarInsuranceCommissionByIdToBill(String id,String time,String uid,String companyId) throws Exception {
        Long timeL=DateUtils.dayToLongTime(time);
        String nowTime=DateUtils.getTimeStr(DateUtils.YYYYMMDD);
        Long nowTimeL=DateUtils.dayToLongTime(nowTime);
        Map<String,Object> map=new HashMap<>();
        if("".equals(companyId)){
            companyId=TokenUtil.getCompanyId(uid);
        }
        //当前时间
        if(timeL>nowTimeL){
            throw new Exception("出单日期日期不正确，不能选择大于今天的时间！！");
        }
        TInsuranceQuotation insuranceQuotation=this.insuranceQuotationService.getInsuranceQuotationById(id);
        String insuranceTypeName="续保";
        if("sb".equals(insuranceQuotation.getInsureType())){
            insuranceTypeName="新保";
        }

        TInsuranceCompany company=companyService.getInfo(insuranceQuotation.getInsuranceCompanyId());
        if(company==null){
            throw new Exception("未找到保险公司!!");
        }
        //获取商业险或交强险项目
        List<Map<String,Object>> jqItems= insuranceQuotationItemService.findQuotationJqItem(insuranceQuotation.getId());
        List<Map<String,Object>> syItems= insuranceQuotationItemService.findQuotationSyItem(insuranceQuotation.getId());
        StringBuffer errStr=new StringBuffer("["+company.getInsuranceCompanyName()+"]   ");
        boolean errFlag=false;
        Map<String,Object> jqMap=new HashMap<>();
        //判断交强险项目是否为空
        if(jqItems.size()>0) {
            jqMap=this.getInsureanceJqAndSy(insuranceQuotation,time,uid,"0",company,companyId);
            if (jqMap == null) {
                if(!String.valueOf(Constant.INSURANCE_PROPERTY.sy.ordinal()).equals(insuranceQuotation.getIscompulsoryinsurance())) {
                    errFlag = true;
                    errStr.append("交强险未设置" + insuranceTypeName + "佣金;");
                }
            }

        }
        Map<String,Object> syMap=new HashMap<>();
        if(syItems.size()>0) {
            syMap=this.getInsureanceJqAndSy(insuranceQuotation,time,uid,"1",company,companyId);
            if (syMap == null) {
                if(!String.valueOf(Constant.INSURANCE_PROPERTY.jq.ordinal()).equals(insuranceQuotation.getIscompulsoryinsurance())) {
                    errFlag = true;
                    errStr.append("商业险未设置" + insuranceTypeName + "佣金;");
                }
            }

        }
        if(errFlag){
            throw new Exception(errStr.toString());
        }
        map.put("jq",jqMap);
        map.put("sy",syMap);
        return map;
    }

    /**
     * 分别获取商业险或交强险佣金信息
     * 1、先取促销佣金 规则优先级：单店、全部
     * 2、在取常规佣金 规则优先级：单点、全部
     * 顺序
     * 促销 单店
     * 促销 全部
     * 常规 单店
     * 常规 全部
     * @param insuranceQuotation
     * @param uid
     * @param type
     * @return
     * @throws Exception
     */
    private Map<String,Object> getInsureanceJqAndSy(TInsuranceQuotation insuranceQuotation,String time,
                                                    String uid,String type,TInsuranceCompany company,String companyId) throws Exception {
        StringBuffer sql=new StringBuffer();
        if("".equals(companyId)) {
            companyId = TokenUtil.getCompanyId(uid);
        }
        Map orginMap=this.organService.info(companyId);
        List<Object> params=new ArrayList<>();
        //单店促销佣金
        sql.append(" select * from (" +
                " select * from T_Insurance_Commission where company_id=? and insure_type=? and (start_date <=? AND " +
                " stop_date >=?) and apply_unit=? and insurance_type=? and status=? ");
        params.add(insuranceQuotation.getInsuranceCompanyId());
        params.add(insuranceQuotation.getInsureType());
        params.add(time);
        params.add(time);
        params.add(TokenUtil.getCompanyId(uid));
        params.add(type);
        params.add(Constant.COMMISSION_STATUS.argee.ordinal());
        if(!"".equals(StringUtil.formatEmpty(insuranceQuotation.getIscompulsoryinsurance()))){
            sql.append(" and iscompulsoryinsurance=? ");
            params.add(insuranceQuotation.getIscompulsoryinsurance());
        }
        sql.append(" and commission_type='1' limit 1 " +
                " ) t1");

        sql.append(" UNION ");
        //指定全部佣金
        sql.append(" select * from ( ");
        sql.append(" select * from T_Insurance_Commission where company_id=? and insure_type=? and (start_date <=? AND " +
                " stop_date >=?) and apply_unit='0'  and insurance_type=? and status=? and area=? ");
        params.add(insuranceQuotation.getInsuranceCompanyId());
        params.add(insuranceQuotation.getInsureType());
        params.add(time);
        params.add(time);
        params.add(type);
        params.add(Constant.COMMISSION_STATUS.argee.ordinal());
        params.add(StringUtil.formatEmpty(orginMap.get("oArea")));
        if(!"".equals(StringUtil.formatEmpty(insuranceQuotation.getIscompulsoryinsurance()))){
            sql.append(" and iscompulsoryinsurance=? ");
            params.add(insuranceQuotation.getIscompulsoryinsurance());
        }
        sql.append(" and commission_type='1' limit 1 ");
        sql.append(" )t ");
        sql.append(" UNION ");
        //促销佣金
        sql.append(" select * from (" +
                " select * from T_Insurance_Commission where company_id=? and insure_type=? and (start_date <=? AND " +
                " stop_date >=?) and apply_unit=? and insurance_type=? and status=? ");
        params.add(insuranceQuotation.getInsuranceCompanyId());
        params.add(insuranceQuotation.getInsureType());
        params.add(time);
        params.add(time);
        params.add(companyId);
        params.add(type);
        params.add(Constant.COMMISSION_STATUS.argee.ordinal());
        if(!"".equals(StringUtil.formatEmpty(insuranceQuotation.getIscompulsoryinsurance()))){
            sql.append(" and iscompulsoryinsurance=? ");
            params.add(insuranceQuotation.getIscompulsoryinsurance());
        }
        sql.append(" and commission_type='0' limit 1 " +
                " ) t1");

        sql.append(" UNION ");
        //指定全部佣金
        sql.append(" select * from ( ");
        sql.append(" select * from T_Insurance_Commission where company_id=? and insure_type=? and (start_date <=? AND " +
                " stop_date >=?) and apply_unit='0'  and insurance_type=? and status=? and area=? ");
        params.add(insuranceQuotation.getInsuranceCompanyId());
        params.add(insuranceQuotation.getInsureType());
        params.add(time);
        params.add(time);
        params.add(type);
        params.add(Constant.COMMISSION_STATUS.argee.ordinal());
        params.add(StringUtil.formatEmpty(orginMap.get("oArea")));
        if(!"".equals(StringUtil.formatEmpty(insuranceQuotation.getIscompulsoryinsurance()))){
            sql.append(" and iscompulsoryinsurance=? ");
            params.add(insuranceQuotation.getIscompulsoryinsurance());
        }
        sql.append(" and commission_type='0' limit 1 ");
        sql.append(" )t ");

        List<Map<String, Object>> mapList=this.itCommissionDao.list(sql.toString(),params.toArray());
        if(mapList.size()==0){
            return null;
        }else {
            return mapList.get(0);
        }
    }

    /**
     * 审核佣金信息
     * @param data
     * @param status
     * @param uid
     * @throws Exception
     */
    @Override
    public void examCommissonStatus(List<Map> data, String status, String uid,String remark) throws Exception {
        if(data!=null){
            if(data.size()>0){
                StringBuffer sql=new StringBuffer();
                sql.append(" update T_Insurance_Commission set status=? where id in ( ");
                List<String> params=new ArrayList<>();
                params.add(status);
                for(int i=0;i<data.size();i++){
                    Map info=data.get(i);
                    sql.append(" ? ");
                    if(i<(data.size()-1)){
                        sql.append(",");
                    }
                    params.add(StringUtil.formatEmpty(info.get("id")));
                }
                sql.append(" ) ");
                this.itCommissionDao.executeSQL(sql.toString(),params.toArray());
                addExamLogs(uid,status,data,remark);
            }else{
                throw new Exception("请选择要审核的佣金!!");
            }
        }else{
            throw new Exception("请选择要审核的佣金!!");
        }
    }

    public void addExamLogs(String uid,String type,List<Map> data,String remark) throws Exception {
        List<TInsuranceCommissionExamLog> logList=new ArrayList<>();
        for(int i=0;i<data.size();i++){
            Map info=data.get(i);
            TInsuranceCommissionExamLog log=new TInsuranceCommissionExamLog();
            log.setCommissionDate(DateUtils.formatLongTime(new Date().getTime(),DateUtils.YYYYMMDD));
            log.setCommissionType(type);
            log.setCommissionId(StringUtil.formatEmpty(info.get("id")));
            log.setCreateTime(new Date().getTime());
            log.setCreateUser(uid);
            log.setRemark(remark);
            logList.add(log);
        }
        this.itCommissionDao.saveOrUpdateList(logList);
    }


    /**
     * 根据佣金ID 获得佣金的审核日志信息
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public List<Map<String, Object>> findExalLogs(String id) throws Exception {
        String sql="select log.*,u.u_name from T_Insurance_COMMISSION_EXAM_LOG log left join t_bc_user u " +
                "ON " +
                "log.create_user=u.id where log.commission_id=?";
        return this.itCommissionDao.list(sql,id);
    }

    /**
     * 停用启用佣金信息
     * @param id
     * @param status
     * @throws Exception
     */
    @Override
    public void enableAndDisableCommission(String id,String status) throws Exception {
        TInsuranceCommission commission=this.itCommissionDao.getInsuranceCommissionById(id);
        commission.setStatus(status);
        this.itCommissionDao.saveOrUpdate(commission);
    }

    /**
     * 获得佣金详情
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public TInsuranceCommission getInfo(String id) throws Exception {
        return this.itCommissionDao.getInsuranceCommissionById(id);
    }

}
